//
//  TimedEvent.Standard.swift
//  Utility
//
//  Created by 何海涛 on 2017/5/25.
//  Copyright © 2017年 何海涛. All rights reserved.
//

import Foundation

/// 一个标准的计时器事件处理协议，包含1个响应方法 - `scheduleTimerFired`
@objc public protocol IStandardTimedEventHandler {
    
    /// 计时器响应方法
    ///
    /// - Parameter timer: 计时器.
    func scheduleTimerFired(timer: Timer)
}

// MARK: - IStandardTimedEventHandler
public extension TimedEvent where TTimeHandler: IStandardTimedEventHandler {
    
    /// 创建标准的计时器事件
    ///
    /// - Parameters:
    ///   - interval: 时间间隔（秒）.
    ///   - autoStart: 是否自动启动。默认`是`
    ///   - fireImmediate: 如果自动启动，启动后是否立即执行。默认`否`
    ///   - repeats: 是否反复执行。默认`是`
    /// - Note: 如果autoStart=true, 请在适当的地方调用`stop`来停止计时器以释放相关资源。
    public init(interval: TimeInterval, autoStart: Bool = true, fireImmediate: Bool = false, repeats: Bool = true) {
        self.init(interval: interval, autoStart: autoStart, fireImmediate: fireImmediate, repeats: repeats) { (handler, timer) in
            handler.scheduleTimerFired(timer: timer)
        }
    }
}

/// TimedEvent<TTimeHandler> where TTimeHandler: IStandardTimedEventHandler
///
///     class TimedEventDemo: IStandardTimedEventHandler {
///         var counter: Int = 0
///         var events = StandardTimedEvent(interval: 2) // 2秒执行一次
///         func run() {
///             events +=? self
///         }
///
///         func scheduleTimerFired(timer: Timer) {
///             print("scheduleTimerFired\(counter)")
///             if (counter == 5) {
///                 events +=? self
///                 // 再注册一次, 注册之后每次scheduleTimerFired会执行两次。
///             }
///             if (counter == 10) {
///                 events.clear()
///                 // 清除之后，scheduleTimerFired不再命中。
///             }
///             counter += 1
///         }
///     }
public typealias StandardTimedEvent = TimedEvent<IStandardTimedEventHandler>
